/*
 * Copyright (c) 2015 Uwantsoft Ltd.
 * www.uwantsoft.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Uwantsoft ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement you
 * entered into with Uwantsoft.
 */

package com.uwantsoft.business.service.domain.user;

import com.uwantsoft.business.facade.dto.user.UserDto;
import com.uwantsoft.constant.Constant;
import com.uwantsoft.util.AbstractEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Chuanbao
 */
@Entity
@Table(name = "user")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class User extends AbstractEntity{
    @Column(name = "username",unique = true)
    protected String username;
    @Column(name = "password")
    protected String password;
    @Column(name = "name")
    protected String name;
    @Column(name = "device_type")
    protected String deviceType;
    @Column(name = "channel_id")
    protected String channelId;

    @Column
    @Enumerated(value = EnumType.STRING)
    protected LoginStatus loginStatus = LoginStatus.OFFLINE;

    public User() {
    }

    public static User createUser(UserDto userDto) {
        User user = new Driver();
        user.username = userDto.getUsername();
        user.password = userDto.getPassword();
        user.name = userDto.getName();
        return user;
    }


    public void update(String username,String password,String name){
        this.username = username;
        this.password = password;
        this.name = name;

    }

    public void deleteUser(){
        this.active(false);
    }

    public String username() {
        return username;
    }

    public String password() {
        return password;
    }

    public String name() {
        return name;
    }

    public LoginStatus loginStatus() {
        return loginStatus;
    }

    public String deviceType() {
        return deviceType;
    }

    public String channelId() {
        return channelId;
    }

    public UserDto convert() {
        UserDto userDto = new UserDto();
        userDto.setGuid(this.guid());
        userDto.setUsername(this.username);
        userDto.setPassword(this.password);
        userDto.setName(this.name);
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(Constant.ROLE_PREFIX+role().name()));
        userDto.setAuthorities(authorities);
        return userDto;
    }

    public abstract Role role();
}
